const http = require('http')
const { URL } = require('url')

const port = 8081

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`)
  if (req.method === 'GET' && url.pathname === '/') {
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end(`<html><body><h1>Hello from Node</h1><p>Try <a href=\"/api/hello\">/api/hello</a> or <a href=\"/api/time\">/api/time</a></p></body></html>`)
    return
  }
  if (req.method === 'GET' && url.pathname === '/api/hello') {
    res.setHeader('Content-Type', 'text/plain; charset=utf-8')
    res.end('Hello Node!')
    return
  }
  if (req.method === 'GET' && url.pathname === '/api/time') {
    res.setHeader('Content-Type', 'application/json')
    res.end(JSON.stringify({ time: new Date().toISOString() }))
    return
  }
  if (req.method === 'POST' && url.pathname === '/api/echo') {
    let body = ''
    req.on('data', (chunk) => { body += chunk })
    req.on('end', () => {
      try {
        const parsed = JSON.parse(body)
        res.setHeader('Content-Type', 'application/json')
        res.end(JSON.stringify({ ok: true, youSent: parsed }))
      } catch (e) {
        res.statusCode = 400
        res.setHeader('Content-Type', 'application/json')
        res.end(JSON.stringify({ ok: false, error: 'invalid json' }))
      }
    })
    return
  }
  res.statusCode = 404
  res.end('Not Found')
})

server.listen(port, () => {
  console.log(`Node server listening on http://127.0.0.1:${port}/`)
})
